﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExtAspNet;
using MyDMS.DAL;

namespace MyDMS_ExtJS
{
    public partial class Project : PageBase
    {
        private MyDMSEntity _myDmsEntity = new MyDMSEntity();
        public string ProjectName = string.Empty;
        private int _proj_code = 0;
        private bool _isAnony = false;
        protected int _dept_code = 0;
        protected int _assgin_code = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 处理参数

            if (Request.QueryString["proj"] != null)
            {
                _proj_code = int.Parse(Request.QueryString["proj"]);
                var firstOrDefault = _myDmsEntity.Project.FirstOrDefault(p => p.Project_Code == _proj_code);
                if (firstOrDefault != null)
                    _assgin_code = firstOrDefault.Assigned_To;
            }
            if (Request.QueryString["dept"] != null)
            {
                _dept_code = int.Parse(Request.QueryString["dept"]);
            }

            #endregion

            if(!IsPostBack)
            {

                btnAdd.OnClientClick =
                    UploadWindow.GetShowReference(
                        string.Format("UploadDocument.aspx?dept={0}&proj={1}", _dept_code,
                                      _proj_code));
            }

            if (Author.role_Code == 3 && Author.department_Code == _dept_code)
            {
                ManagePanel.Hidden = false;
                BindgvManageData();
            }
            else
            {
                ManagePanel.Hidden = true;
            }


            _isAnony = _myDmsEntity.Project.FirstOrDefault(p => p.Project_Code == _proj_code).Is_Anonymous;
            if (Author.department_Code == _dept_code || _isAnony)
            {
                BindgvDocumentsData();
            }

        }


        #region 数据绑定

        private void BindgvDocumentsData()
        {
            var query = from t in _myDmsEntity.Task.Where(t => t.Project_Code == _proj_code)
                        from d in _myDmsEntity.Document.Where(d => d.Task_Code == t.Task_Code)
                        select new
                        {
                            d.Document_Code,
                            d.Document_Desc,
                            d.Document_Name,
                            TaskName = t.Task_Title,
                            FolderName = _myDmsEntity.Folder.FirstOrDefault(f => f.Folder_Code == d.Folder_Code).Folder_Title,
                            OwnerName =
                 _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).FirstName +
                 _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).LastName,
                            SecretLevelName = _myDmsEntity.SecretLevel.FirstOrDefault(sl => sl.SecretLevel_Code == d.SecretLevel_Code).SecretLevel_Name,
                            ShelfLifeName = _myDmsEntity.ShelfLife.FirstOrDefault(s => s.ShelfLife_Code == d.ShelfLife_Code).ShelfLife_Name,
                            d.Updation_Date
                        };
            DataTable table = query.CopyToDataTable();
            DataView view = table.DefaultView;
            gvDocuments.DataSource = view;
            gvDocuments.DataBind();
        }

        private void BindgvManageData()
        {
            var query = _myDmsEntity.Task.Where(t => t.Project_Code == _proj_code);
            DataTable table = query.CopyToDataTable();
            DataView view = table.DefaultView;
            gvManage.DataSource = view;
            gvManage.DataBind();
        }

        #endregion

        #region 排序

        protected void gvDocuments_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            var query = from t in _myDmsEntity.Task.Where(t => t.Project_Code == _proj_code)
                        from d in _myDmsEntity.Document.Where(d => d.Task_Code == t.Task_Code)
                        select new
                        {
                            d.Document_Code,
                            d.Document_Desc,
                            d.Document_Name,
                            TaskName = t.Task_Title,
                            FolderName = _myDmsEntity.Folder.FirstOrDefault(f => f.Folder_Code == d.Folder_Code).Folder_Title,
                            OwnerName =
                 _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).FirstName +
                 _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).LastName,
                            SecretLevelName = _myDmsEntity.SecretLevel.FirstOrDefault(sl => sl.SecretLevel_Code == d.SecretLevel_Code).SecretLevel_Name,
                            ShelfLifeName = _myDmsEntity.ShelfLife.FirstOrDefault(s => s.ShelfLife_Code == d.ShelfLife_Code).ShelfLife_Name,
                            d.Updation_Date
                        };
            DataTable table = query.CopyToDataTable();
            DataView view = table.DefaultView;
            gvDocuments.DataSource = view;
            view.Sort = String.Format("{0} {1}", e.SortField, e.SortDirection);
            gvDocuments.DataBind();
        }

        protected void gvManage_Sort(object sender, ExtAspNet.GridSortEventArgs e)
        {
            var query = _myDmsEntity.Task.Where(t => t.Project_Code == _proj_code);
            DataTable table = query.CopyToDataTable();
            DataView view = table.DefaultView;
            gvManage.DataSource = view;
            view.Sort = String.Format("{0} {1}", e.SortField, e.SortDirection);
        }
        #endregion

        #region 分页

        protected void gvDocuments_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gvDocuments.PageIndex = e.NewPageIndex;
        }

        protected void gvManage_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gvManage.PageIndex = e.NewPageIndex;
        }

        #endregion

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            var result = from tt in _myDmsEntity.Task.Where(t => t.Project_Code == _proj_code)
                       from d in _myDmsEntity.Document.Where(d => d.Task_Code == tt.Task_Code)
                       select new
                                  {
                                      d.Document_Code,
                                      d.Document_Desc,
                                      d.Document_Name,
                                      d.Document_Type,
                                      d.Creation_Date,
                                      TaskName =
                           _myDmsEntity.Task.FirstOrDefault(t => t.Task_Code == d.Task_Code).Task_Title,
                                      FolderName =
                           _myDmsEntity.Folder.FirstOrDefault(f => f.Folder_Code == d.Folder_Code).Folder_Title,
                                      OwnerName =
                           _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).FirstName +
                           _myDmsEntity.User.FirstOrDefault(u => u.User_Code == d.Owner).LastName,
                                      SecretLevelName =
                           _myDmsEntity.SecretLevel.FirstOrDefault(sl => sl.SecretLevel_Code == d.SecretLevel_Code).
                           SecretLevel_Name,
                                      ShelfLifeName =
                           _myDmsEntity.ShelfLife.FirstOrDefault(s => s.ShelfLife_Code == d.ShelfLife_Code).
                           ShelfLife_Name,
                                      d.Updation_Date
                                  };
            if (!string.IsNullOrEmpty(ddlDocumentType.SelectedValue))
            {
                var type = Convert.ToInt32(ddlDocumentType.SelectedValue);
                result = result.Where(d => d.Document_Type == type);
            }
            if (dpEnd.SelectedDate.HasValue && dpStart.SelectedDate.HasValue)
            {
                result =
                    result.Where(
                        d =>
                        d.Creation_Date >= dpStart.SelectedDate.Value && d.Creation_Date <= dpEnd.SelectedDate.Value);
            }
            if (!string.IsNullOrEmpty(tbKeyWord.Text))
            {
                result = result.Where(d => d.Document_Name.Contains(tbKeyWord.Text));
            }
            gvDocuments.DataSource = result;
            gvDocuments.DataBind();
        }
        protected void btnDel_Click(object sender, EventArgs e)
        {
            int selectedCount = gvDocuments.SelectedRowIndexArray.Length;
            if (selectedCount > 0)
            {
                for (int i = 0; i < selectedCount; i++)
                {
                    int rowIndex = gvDocuments.SelectedRowIndexArray[i];
                    var docCode = Convert.ToInt32(gvDocuments.DataKeys[rowIndex][0]);
                    var selectDoc =
                        _myDmsEntity.Document.FirstOrDefault(
                            d => d.Document_Code == docCode);
                    if (selectDoc.Owner != Author.user_Code)
                    {
                        Alert.ShowInTop("你不是文档“" + selectDoc.Document_Name + "”的负责人，无权删除。");
                    }
                    else
                    {
                        _myDmsEntity.Document.DeleteObject(selectDoc);
                        _myDmsEntity.SaveChanges();
                    }
                }
            }
            BindgvDocumentsData();
        }
        protected void btnView_Click(object sender, EventArgs e)
        {
            int rowIndex = gvDocuments.SelectedRowIndexArray[0];
            var docCode = Convert.ToInt32(gvDocuments.DataKeys[rowIndex][0]);
            var selectDoc =
                _myDmsEntity.Document.FirstOrDefault(
                    d => d.Document_Code == docCode);
            PageContext.RegisterStartupScript(
                    DocEditorWindow.GetShowReference(
                        string.Format("DocEditor/DocEditor.aspx?dept={0}&proj={1}&id={2}&doctype={3}&act={4}", _dept_code,
                                      _proj_code,  docCode, selectDoc.File_Path.Split('.').Last().ToLower(), "open")));
        }
        protected void btnPrint_Click(object sender, EventArgs e)
        {
            int rowIndex = gvDocuments.SelectedRowIndexArray[0];
            var docCode = Convert.ToInt32(gvDocuments.DataKeys[rowIndex][0]);
            var selectDoc =
                _myDmsEntity.Document.FirstOrDefault(
                    d => d.Document_Code == docCode);
            PageContext.RegisterStartupScript(
                    DocEditorWindow.GetShowReference(
                        string.Format("DocEditor/DocEditor.aspx?dept={0}&proj={1}&id={2}&doctype={3}&act={4}", _dept_code,
                                      _proj_code, docCode, selectDoc.File_Path.Split('.').Last().ToLower(), "print")));
        }
        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            ExtAspNet.PageContext.Refresh();
        }
        protected void btnMenu_Click(object sender, EventArgs e)
        {
            var result = string.Empty;
            foreach (var i in gvManage.SelectedRowIndexArray)
            {
                result += (gvManage.DataKeys[i][0] + ",");
            }
            PageContext.RegisterStartupScript(
                DocEditorWindow.GetShowReference(
                    string.Format("PrintMenu.aspx?task={0}", result)));
        }
    }
}